﻿Imports System
Imports System.IO
Imports System.Security.Cryptography
Imports System.Globalization

Public Class Encryptor
    Private transformer As EncryptTransformer

    Private initVec As Byte()

    Private encKey As Byte()


    Public Property IV() As Byte()
        Get
            Return initVec
        End Get

        Set(ByVal value As Byte())
            initVec = value
        End Set
    End Property

    Public ReadOnly Property Key() As Byte()
        Get
            Return encKey
        End Get
    End Property

    Public Sub New(ByVal algId As EncryptionAlgorithm)
        transformer = New EncryptTransformer(algId)
    End Sub

    Public Function Encrypt(ByVal bytesData As Byte(), ByVal bytesKey As Byte()) As Byte()
        Dim memoryStream As New MemoryStream()
        transformer.IV = initVec
        Dim iCryptoTransform As ICryptoTransform = transformer.GetCryptoServiceProvider(bytesKey)
        Dim cryptoStream As New CryptoStream(memoryStream, iCryptoTransform, CryptoStreamMode.Write)
        Try
            cryptoStream.Write(bytesData, 0, CInt(bytesData.Length))
        Catch e As Exception            
            Throw New Exception([String].Concat("Error while writing encrypted data to the stream: ", e.Message))
        End Try
        encKey = transformer.Key
        initVec = transformer.IV
        cryptoStream.FlushFinalBlock()
        cryptoStream.Close()
        Return memoryStream.ToArray()
    End Function

    Private Shared Function HexStringToByteArray(ByVal str As String) As Byte()
        Dim buffer As Byte()

        If str Is Nothing Then
            Throw New ArgumentNullException("str")
        End If

        If str.Length Mod 2 = 1 Then
            str = "0"c & str
        End If

        buffer = New Byte(str.Length \ 2 - 1) {}

        For i As Integer = 0 To buffer.Length - 1
            buffer(i) = Byte.Parse(str.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture)
        Next

        Return buffer
    End Function

End Class
